package com.gla.market.activity;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.gla.market.R;
import com.gla.market.constant.Constants;
import com.gla.market.fragments.AboutMe;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PerSettingActivity extends AppCompatActivity {

    Button back,commit;
    EditText user_name2,old_password2,new_password2,confirm_password2;
    RelativeLayout my_head;
    ImageView login_is_show_pwd,login_is_show_pwd2,login_is_show_pwd3;

    String name,pwd;
    int id;

    private boolean isHide = true;  //输入框密码是否是隐藏，默认为是
    private boolean isHide2 = true;
    private boolean isHide3 = true;
    int flag = 0;


    private void initView() {
        back = findViewById(R.id.back);
        user_name2 = findViewById(R.id.user_name2);
        old_password2 = findViewById(R.id.old_password2);
        new_password2 = findViewById(R.id.new_password2);
        confirm_password2 = findViewById(R.id.confirm_password2);
        commit = findViewById(R.id.commit);
        my_head = findViewById(R.id.my_head);
        login_is_show_pwd = findViewById(R.id.login_is_show_pwd);
        login_is_show_pwd2 = findViewById(R.id.login_is_show_pwd2);
        login_is_show_pwd3 = findViewById(R.id.login_is_show_pwd3);
        //设置ImageView的初始图标为隐藏
        login_is_show_pwd.setImageResource(R.drawable.hhn_hide);
        login_is_show_pwd2.setImageResource(R.drawable.hhn_hide);
        login_is_show_pwd3.setImageResource(R.drawable.hhn_hide);

        //从shareprefences中读取用户的id和密码
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        id = sharedPreferences.getInt("user_id",0);
        pwd = sharedPreferences.getString("password","0");
        name = sharedPreferences.getString("name","0");
        user_name2.setText(name);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_per_setting);
        initView();
        //返回按钮
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //提交按钮点击事件
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!validate()) {
                    perSetingFailed();
                    return;
                }
                if (flag == 1){
                    upName();
                }else{
                    upPwd();
                }

            }
        });
        //更改头像按钮点击事件
        my_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PerSettingActivity.this,LoadPictureActivity.class);
                startActivity(intent);
                finish();
            }
        });
        //隐藏密码按钮点击事件
       login_is_show_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isShowPassword();
            }
        });
        login_is_show_pwd2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isShowPassword2();
            }
        });
        login_is_show_pwd3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isShowPassword3();
            }
        });
    }
    private void isShowPassword() {
        if(isHide == true) {
            login_is_show_pwd.setImageResource(R.drawable.hhn_nohide);
            //密文
            HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
            old_password2.setTransformationMethod(method1);
            isHide = false;
        } else {
            login_is_show_pwd.setImageResource(R.drawable.hhn_hide);
            //密文
            TransformationMethod method2 = PasswordTransformationMethod.getInstance();
            old_password2.setTransformationMethod(method2);
            isHide = true;
        }
        //重置光标位置
        int index = old_password2.getText().toString().length();
        old_password2.setSelection(index) ;
    }
    private void isShowPassword2() {
        if(isHide2 == true) {
            login_is_show_pwd2.setImageResource(R.drawable.hhn_nohide);
            //密文
            HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
            new_password2.setTransformationMethod(method1);
            isHide2 = false;
        } else {
            login_is_show_pwd2.setImageResource(R.drawable.hhn_hide);
            //密文
            TransformationMethod method2 = PasswordTransformationMethod.getInstance();
            new_password2.setTransformationMethod(method2);
            isHide2 = true;
        }
        //重置光标位置
        int index = new_password2.getText().toString().length();
        new_password2.setSelection(index) ;
    }
    private void isShowPassword3() {
        if(isHide3 == true) {
            login_is_show_pwd3.setImageResource(R.drawable.hhn_nohide);
            //密文
            HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
            confirm_password2.setTransformationMethod(method1);
            isHide3 = false;
        } else {
            login_is_show_pwd3.setImageResource(R.drawable.hhn_hide);
            //密文
            TransformationMethod method2 = PasswordTransformationMethod.getInstance();
            confirm_password2.setTransformationMethod(method2);
            isHide3 = true;
        }
        //重置光标位置
        int index = confirm_password2.getText().toString().length();
        confirm_password2.setSelection(index) ;
    }
//修改个人信息
    private void upPwd() {


        String username = user_name2.getText().toString();
        String newpwd = new_password2.getText().toString();
        String confirmpwd = confirm_password2.getText().toString();

        if (!confirmpwd.equals(newpwd)) {
            new_password2.setError("两次密码输入不一致！");
        } else {
            postPerSettingRequest(username,newpwd);
        }
    }

    //修改名字
    private void upName() {

        String username = user_name2.getText().toString();
        postNameSettingRequest(username);

    }
    //修改个人信息
    private void postPerSettingRequest(String userName, String password) {
        //更新sp数据
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE); //私有数据
        //保存用户信息
        Log.d("result","修改个人信息更新成功");
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("name", userName);
        editor.putString("password", password);
        editor.commit();//提交修改
        //post请求来获得数据
        //创建一个RequestBody，存放重要数据的键值对
        RequestBody body = new FormBody.Builder()
                .add("id",String.valueOf(id))
                .add("name", userName)
                .add("password", password).build();

        //发送修改请求
        NetUtil.doPost(Constants.BASE_URL + Constants.MODIFY_USER_INFO_URL + id, body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = -1;
                mHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                Message message = Message.obtain();
                //获取返回结果
                String result = response.body().string().trim();
                Log.d("result",result);
                try {
                        JSONObject json = JSON.parseObject(result);
                        if (json.getInteger("status")==0) {
                            message.what = 1;
                        } else {
                            message.what = 0;
                        }
                    } catch (Exception e) {
                    Log.e("network error!", e.getMessage());
                    message.what = 0;
                    message.obj = "请求响应失败！";
                }
                mHandler.sendMessage(message);
            }
        });
    }

    //修改昵称
    private void postNameSettingRequest(String userName) {
        String oldpwd = old_password2.getText().toString();
        String newpwd = new_password2.getText().toString();
        String confirmpwd = confirm_password2.getText().toString();
        SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE); //私有数据
        //保存用户信息
        Log.d("result","修改昵称更新成功");
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("name", userName);
        editor.commit();//提交修改
        //post请求来获得数据
        //创建一个RequestBody，存放重要数据的键值对
        RequestBody body = new FormBody.Builder()
                .add("id",String.valueOf(id))
                .add("name", userName).build();

        //发送修改请求
        NetUtil.doPost(Constants.BASE_URL + Constants.MODIFY_USER_NAME_URL + id, body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = -1;
                sHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                Message message = Message.obtain();
                //获取返回结果
                String result = response.body().string().trim();
                Log.d("result",result);
                try {
                    JSONObject json = JSON.parseObject(result);
                    if (json.getInteger("status")==0) {
                        if (!name.equalsIgnoreCase(userName) && "".equals(oldpwd) &&
                        "".equals(newpwd) && "".equals(confirmpwd)){
                            message.what = 1;
                        }
                    } else {
                        message.what = 0;
                    }
                } catch (Exception e) {
                    Log.e("network error!", e.getMessage());
                    message.what = 0;
                    message.obj = "请求响应失败！";
                }
                sHandler.sendMessage(message);
            }
        });
    }

    /**
     * 修改个人信息handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    perSetingSuccess();
                    break;
                default:
                    perSetingFailed();
                    break;
            }
        }
    };
    //修改名字handler
    private Handler sHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    nameSetingSuccess();
                    break;
                default:
                    nameSetingFailed();
                    break;
            }
        }
    };

    public boolean validate() {
        boolean valid = true;

        String username = user_name2.getText().toString();
        String oldpwd = old_password2.getText().toString();
        String newpwd = new_password2.getText().toString();
        String confirmpwd = confirm_password2.getText().toString();

        //昵称错误
        if (TextUtils.isEmpty(username)) {
            user_name2.setError("昵称不能为空");
            valid = false;
            System.out.println(1);
        } else if (username.length()>10){
            user_name2.setError("昵称长度不得超过10，请修改！");
            valid = false;
            System.out.println(2);
        }

        if (!("".equals(oldpwd) && "".equals(newpwd) && "".equals(confirmpwd))){
            //旧密码错误
            if (oldpwd.isEmpty()) {
                old_password2.setError("请输入原始密码！");
                valid = false;

            } else if(!oldpwd.equalsIgnoreCase(pwd)){
                old_password2.setError("输入的密码与原密码不一样");
                valid = false;
            }
            //新密码错误
            if (newpwd.isEmpty()) {
                new_password2.setError("请输入新密码！");
                valid = false;
            }
            else if (newpwd.isEmpty() || newpwd.length() < 4 || newpwd.length() > 10) {
                new_password2.setError("请输入4-10位密码");
                valid = false;
            }
            //重复密码时错误
            if (confirmpwd.isEmpty()) {
                confirm_password2.setError("请输入确认密码！");
                valid = false;
            }else if(!newpwd.equalsIgnoreCase(confirmpwd)){
                confirm_password2.setError("两次密码不一致");
            }
        }else{
            flag = 1;
        }

        Log.d("result",oldpwd);
        Log.d("result2",newpwd);
        return valid;
    }
//修改个人信息
    public void perSetingSuccess() {
        Toast.makeText(this, "修改成功,请重新登陆!", Toast.LENGTH_SHORT).show();
        commit.setEnabled(true);
        //清空userInfo的信息
        SharedPreferencesUtil.clear(PerSettingActivity.this,"userInfo");
        Intent intent = new Intent(AboutMe.UPDATE);
        sendBroadcast(intent);
        finish();

    }

    public void perSetingFailed() {
        Toast.makeText(getBaseContext(), "修改失败", Toast.LENGTH_LONG).show();
        commit.setEnabled(true);
    }
//修改名字
    public void nameSetingSuccess() {
        Toast.makeText(this, "修改昵称成功!", Toast.LENGTH_SHORT).show();
        commit.setEnabled(true);
        //发送广播，更新信息
        Intent intent = new Intent(AboutMe.UPDATE);
        sendBroadcast(intent);
        finish();
    }

        public void nameSetingFailed() {
            Toast.makeText(getBaseContext(), "修改失败", Toast.LENGTH_LONG).show();
            commit.setEnabled(true);
        }

}